#include "stdafx.h"
#include "Device.h"
#include "ChildView.h"
#include "CADDoc.h"


CString Device::__stationName(L"NO");
int     Device::__stationID = 0;

CPen Device::__SECTION_PEN;
CPen Device::__SEAL_PEN;
CPen Device::__INSU_PEN;
CBrush Device::__SIGNAL_BRUSH[3];

int Device::__sectionWidth = 2;
int Device::__sealWidth    = 1;
int Device::__insuWidth    = 2;
int Device::__insuHeight   = 6;

int Device::__signalR = 16;

int Device::__dgree        = 60;
int Device::__switchHeight = 0;
int Device::__nailHeight   = 0;
int Device::__nailX        = 0;


Device::Device(void)
{
	_data._stationID = __stationID;
	_bSealed         = false;
}


Device::~Device(void)
{
}


void Device::Serialize(CArchive& ar)
{
	Graphic::Serialize(ar);
	_data.Serialize(ar);
}


void Device::drawMutiLine(CPaintDC& dc, CPoint pt[], int nPt)
{
	dc.MoveTo(pt[0]);

	for (int i = 1; i < nPt; i++)
	{
		dc.LineTo(pt[i]);
	}
}


void Device::drawMutiInsu(CPaintDC& dc, CPoint pt[], int nPt)
{
	for (int i = 0; i < nPt; i += 2)
	{
		dc.MoveTo(pt[i]);
		dc.LineTo(pt[i + 1]);
	}
}


Device* Device::GetDevByID(int id, int devTypeBegin, int devTypeEnd)
{
	return static_cast<CChildView*>(__pWnd)->GetDocument()->getDevByID(id, devTypeBegin, devTypeEnd);
}

BEGIN_MESSAGE_MAP(Device, Graphic)
	ON_WM_MOUSELEAVE()
	ON_WM_MOUSEMOVE()
	ON_WM_WINDOWPOSCHANGED()
END_MESSAGE_MAP()


void Device::OnMouseLeave()
{
	_bSealed = false;
	Invalidate();

	Graphic::OnMouseLeave();
}


void Device::OnMouseMove(UINT nFlags, CPoint point)
{
	TRACKMOUSEEVENT time;       
	time.cbSize      = sizeof(TRACKMOUSEEVENT);       
	time.dwFlags     = TME_HOVER | TME_LEAVE;       
	time.dwHoverTime = HOVER_DEFAULT;     
	time.hwndTrack   = m_hWnd;   
	_TrackMouseEvent(&time);  

	_bSealed = true;
	Invalidate();

	Graphic::OnMouseMove(nFlags, point);
}


void Device::drawSealFrame(CPaintDC& dc, CPoint sealPt[], int nPt)
{
	if (_bSealed)
	{
		dc.SelectObject(__SEAL_PEN);
		drawMutiLine(dc, sealPt, nPt);
		dc.LineTo(sealPt[0]);
	}
}


CPoint Device::getCrossPoint(CPoint& line1Pt1, CPoint& line1Pt2, CPoint& line2Pt1, CPoint& line2Pt2)
{
	double a1 = (double)(line1Pt2.y - line1Pt1.y) / (double)(line1Pt2.x - line1Pt1.x);
	double b1 = line1Pt1.y - a1 * (double)line1Pt1.x;

	double a2 = (double)(line2Pt2.y - line2Pt1.y) / (double)(line2Pt2.x - line2Pt1.x);
	double b2 = line2Pt1.y - a2 * (double)line2Pt1.x;

	double x = (b2 - b1) / (a1 - a2);
	double y = a1 * x + b1;

	return CPoint((int)x, (int)y);
}


void Device::OnWindowPosChanged(WINDOWPOS* lpwndpos)
{
	Graphic::OnWindowPosChanged(lpwndpos);

	setNamePos();
	_data._name.Invalidate();
}


void Device::swapPoint(CPoint& pt1, CPoint& pt2)
{
	CPoint tmpPt = pt1;
	pt1 =  pt2;
	pt2 = tmpPt;
}